import cn.edu.dgut.sai.demo.jpa.Entity.Student;
import cn.edu.dgut.sai.demo.jpa.Entity.Course;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "studentservlet",urlPatterns = {"/servlet"})
public class studentservlet extends HttpServlet {
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        EntityManager em = entityManagerFactory.createEntityManager();
        EntityTransaction tx = em.getTransaction();

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String xuehao = request.getParameter("xuehao");
        String sex = request.getParameter("sex");
        String ids = request.getParameter("ids");
        String names = request.getParameter("names");
        String time = request.getParameter("time");

        Course course=new Course(ids,names,time);
        Student student=new Student(id,name,xuehao,sex,course);
        tx.begin();
        em.persist(student);
        em.persist(course);
        tx.commit();
        em.close();
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println("添加记录成功");
    }
}
